<template>
  <div class="form-setting-panel">
    <!-- start 标题 -->
    <form-title-setting
      :field="field"
      :mode="mode"
      :setting="{name: $t('common.form.type.select')}"
      :disabled="true"
    ></form-title-setting>
    <!-- end 标题 -->

    <!-- start 描述信息 -->
    <form-describe-setting
      :field="field"
      :mode="mode"
      @input="updateForDom"
    ></form-describe-setting>
    <!-- end 描述信息 -->

    <!-- start 校验 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{$t('common.base.check')}}</h4>
      <div class="form-item-box">
        <!-- 必填 -->
        <form-required-setting
          :field="field"
          :disabled="true"
        ></form-required-setting>
      </div>
    </div>
    <!-- end 校验 -->

    <!-- start 选项 -->
    <div class="form-setting-options">
      <div class="form-select-setting-list">
        <div class="list-group">
          <div
            v-for="(option, index) in options"
            :key="index"
            class="form-select-setting-option"
          >
            <input
              type="text"
              :value="option.value.text"
              :disabled="true"
            />
            <template v-if="!field.isMulti">
              <button
                type="button"
                :class="[
                  'btn-text',
                  'form-select-setting-default',
                  option.isDefault && 'btn-active',
                ]"
                @click="setDefaultOption({value: option.value.text})"
              >
                <i class="iconfont icon-check-fill"></i>
              </button>
            </template>
          </div>
        </div>
      </div>
    </div>
    <!-- end 选项 -->

    <!-- start 选项显示模式 -->
    <form-displaymode-setting
      :field="field"
      @input="update"
    ></form-displaymode-setting>
    <!-- end 选项显示模式 -->

    <!-- start 批量编辑选项 -->
    <base-modal
      :title="$t('common.base.batchEditOptions')"
      width="520px"
      class="form-select-setting-modal"
      :show.sync="batchModalShow"
      :mask-closeable="false"
    >
      <div class="form-select-setting-batch">
        <textarea
          :value="optionText"
          @input="updateOptionText"
          rows="10"
        ></textarea>
        <div class="form-select-setting-warn" v-if="errMessage">
          {{ errMessage }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="form-select-tips">{{$t('common.base.everyLinePointToOneOption')}}</span>
        <el-button @click="batchModalShow = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="batchEdit">{{$t('common.base.save')}}</el-button>
      </div>
    </base-modal>
    <!-- end 批量编辑选项 -->
  </div>
</template>

<script>
import {
  SELECT_OPTION_LENGTH_MAX,
  FORM_FIELD_LOGICAL_DISABLE,
  SELECT_OPTION_MAX,
} from '@src/component/form/config';

import _ from 'lodash';
import draggable from 'vuedraggable';
import LogicalFieldModal from '../components/LogicalFieldModal';
import SettingMixin from '@src/component/form/mixin/setting';
import FormSelectMixin from '@src/component/form/mixin/form.select';
import { settingProps } from '@src/component/form/components/props';
import Platform from '@src/platform';
/* enum */
import TableNameEnum from '@model/enum/TableNameEnum.ts';
import i18n from '@src/locales'

export default {
  name: 'form-select-setting-solve-status',
  mixins: [SettingMixin, FormSelectMixin],
  props: {
    ...settingProps,
    /** 用于获取FormDesign实例 */
    getContext: Function,
  },
  computed: {
    /**
     * 满足以下条件允许配置显示逻辑：
     * 1. 单选
     * 2. 不是最后一个非分割线类型的非系统字段
     */
    allowLogical() {
      if (this.field.isMulti) return false;

      // let context = this.getContext();
      // let fields = context.value;

      // let currIndex = fields.findIndex(f => f.fieldName == this.field.fieldName);

      // for(let i = fields.length - 1; i > currIndex; i--){
      //   let field = fields[i];
      //   if(field.isSystem == 0 && FORM_FIELD_LOGICAL_DISABLE.indexOf(field.formType) < 0){
      //     return true;
      //   }
      // }

      return true;
    },
    /** 该字段配置的逻辑显示项 */
    logical() {
      let logical = {};

      let context = this.getContext();
      let fields = context.value;

      let fieldName = this.field.fieldName;
      let options = this.options;

      for (let i = 0; i < fields.length; i++) {
        let field = fields[i];

        let dependencies = field.dependencies;
        if (_.isEmpty(dependencies)) continue;

        let depValues = dependencies[fieldName];
        if (!Array.isArray(depValues) || depValues.length == 0) continue;

        for (let j = 0; j < depValues.length; j++) {
          let val = depValues[j];
          if (null == logical[val]) {
            logical[val] = {
              index: options.findIndex(i => i.value == val),
              controls: [],
            };
          }

          logical[val].controls.push(field.displayName);
        }
      }

      return logical;
    },
    optionMaxLength() {
      return SELECT_OPTION_LENGTH_MAX;
    },
    // 是否是附加组件表单
    isTaskCardForm() {
      return (
        [
          TableNameEnum.TaskCard,
          TableNameEnum.CustomerCard,
          TableNameEnum.ProductCard,
        ].indexOf(this.mode) > -1
      );
    },
  },
  data() {
    return {
      index: this.field.options.length,
      batchModalShow: false,
      optionText: '', // 批量编辑文本
      errMessage: null,
    };
  },
  methods: {
    updateDependencies(val) {
      this.$emit('input', {
        prop: 'dependencies',
        value: val,
        operate: 'update',
      });
    },
    showLogicalModal() {
      let context = this.getContext();
      this.$refs.logical.showModal(this.field, context.value);
    },
    updateOption(event, option) {
      option.value = event.target.value;

      this.$emit('input', {
        value: this.field,
        prop: 'dependencies',
        operate: 'delete',
      });
    },
    delOption(option, index) {
      if (this.options.length <= 1) return alert(this.$t('common.base.tip.evenHaveOneOption2'));

      // 如果是删除默认值，清空默认值
      if (option.isDefault)
        this.$emit('input', { value: null, prop: 'defaultValue' });

      let options = _.cloneDeep(this.options);
      options.splice(index, 1);

      this.$emit('input', { value: options, prop: 'options' });
      this.$emit('input', {
        value: this.field,
        prop: 'dependencies',
        operate: 'delete',
      });
    },
    batchEdit() {
      let newValues = this.optionText.split('\n').filter(option => option);
      if (!newValues.length) {
        Platform.alert(this.$t('common.base.tip.evenHaveOneOption2'));
        return false;
      }

      this.errMessage = this.validateOptions(newValues);
      if (this.errMessage) return false;

      let newOptions = newValues.map(item => ({
        value: item,
        isDefault: false,
      }));
      // 补全默认值
      if (!this.field.isMulti) {
        let defaultValue = this.field.defaultValue;
        for (let i = 0; i < newOptions.length; i++) {
          let option = newOptions[i];
          if (defaultValue == option.value) {
            option.isDefault = true;
            break;
          }
        }
      }
      this.$emit('input', { value: newOptions, prop: 'options' });
      this.$emit('input', {
        value: this.field,
        prop: 'dependencies',
        operate: 'delete',
      });

      this.batchModalShow = false;
    },
  },
  components: {
    draggable,
    [LogicalFieldModal.name]: LogicalFieldModal,
    'form-select-logical': {
      name: 'form-select-logical',
      functional: true,
      props: {
        logical: {
          type: Object,
          default: () => ({}),
        },
      },
      render(h, context) {
        let logical = context.props.logical;
        let keys = Object.keys(logical);

        if (keys.length == 0)
          return <p class="form-select-logical-tip">{i18n.t('common.form.tip.fieldNotSetVision')}</p>;

        let controls = keys
          .sort((p, n) => logical[p].index - logical[n].index)
          .map(key => {
            let c = logical[key].controls;

            return (
              <div class="form-select-logical-item">
                <h4>{key}</h4>
                {c.map(i => (
                  <p>{i}</p>
                ))}
              </div>
            );
          });

        return <div>{controls}</div>;
      },
    },
  },
};
</script>
